package parser

import (
	"encoding/json"
	"fmt"
	"gitee.com/pkg/root"
	"gitee.com/pkg/utils/flag"
	"gitee.com/pkg/vvlog"
	v1 "gitee.com/samples/parser/pkg/api/v1"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"path/filepath"
)

var (
	logger    = vvlog.NewLogger("parser.go")
	filePath  string
	parserCmd = &cobra.Command{
		Use:   "parser",
		Short: "parser demo",
		RunE: func(c *cobra.Command, args []string) error {
			flag.PrintFlags(c.Flags())
			logger.Info("to do ")
			data, err := runc()
			if err == nil {
				fmt.Println(data)
				writef(data)
			}
			return err
		},
	}
)

func init() {
	parserCmd.PersistentFlags().StringVarP(&filePath, "f", "f", "test.yaml", "parse file path")
	root.AddCmd(parserCmd)
}

func writef(data *v1.Hello) {
	outputFile, err := os.Create("." + filePath)
	if err != nil {
		return
	}
	defer func() { _ = outputFile.Close() }()
	var b []byte
	switch filepath.Ext(filePath) {
	case ".yaml":
		b, err = yaml.Marshal(data)
	case ".json":
		b, err = json.Marshal(data)
	}
	if err == nil {
		outputFile.Write(b)
	}

}

func runc() (*v1.Hello, error) {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	ref := &v1.Hello{}
	switch filepath.Ext(filePath) {
	case ".yaml":
		return ref, yaml.Unmarshal(data, ref)
	case ".json":
		return ref, json.Unmarshal(data, ref)
	default:
		return nil, nil
	}
}
